<?php
/**
 * Created by PhpStorm.
 * User: 盛茂国
 * Tel: 18394333958
 * Date: 2020/6/2
 * Time: 10:31
 */

namespace app\admin\controller;


use app\admin\model\Preshop;
use app\api\controller\Sms;
use app\common\controller\Backend;
use think\Db;
use think\Request;

class Sellerbuy extends Backend
{
    protected $noNeedRight=[];
    protected $noNeedLogin=[];

    protected $model=null;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->model=new \app\admin\model\Shop();
    }


    //商品库列表
    public function index()
    {
        $obj=$this->model->order('shopid desc')->select();
        $collect=collection($obj);
        $shoparr=$collect->toArray();

        foreach ($shoparr as $list=>$item){
            $srcs=$item['shop_image'];
            $srcsarr=explode(',',$srcs);
            $shoparr[$list]['shop_image']="";
            if(is_array($srcsarr)){
                foreach ($srcsarr as $vo){
                    $shoparr[$list]['shop_image'].="<img src=$vo width='40' height='40'>";
                }
            }else{
                $shoparr[$list]['shop_image']=$srcsarr;
            }

        }
        //print_r($shoparr);die;
        $this->assign('shop',$shoparr);
        return $this->fetch();
    }
    public function preselect(Request $request){
        if($request->isPost()){
            $adminid=$this->auth->id;
            $params=$request->post('btSelectItem/a');

            if(!empty($params)){
                $obj=$this->model->where('shopid','in',implode(',',$params))->select();
                $shoparr=collection($obj)->toArray();


                $smodel=new \app\admin\model\Store();

                $sobj=$smodel->where('admin_id','=',$adminid)->select();
                $store=collection($sobj)->toArray();
            }else{
                return $this->error('请选择要提交的商品');
            }
        }else{
            return $this->error('非法提交');
        }
        $this->assign('store',$store);
        $this->assign('sshop',$shoparr);
        return $this->fetch();
    }
    public function handle(Request $request){
        if($request->isPost()){
            $params=$request->post('row/a');
            $data=[];

            foreach ($params['shopid'] as $k=>$shopid){
                $data[$k]['shopid']=$shopid;
            }
            foreach ($params['shopname'] as $k=>$shopname){
                $data[$k]['shopname']=$shopname;
            }
            foreach ($params['price'] as $k=>$price){
                $data[$k]['price']=$price;
            }
            foreach ($params['number'] as $k=>$number){
                $data[$k]['number']=$number;
            }
            foreach ($params['storeid'] as $k=>$storeid){
                $data[$k]['storeid']=$storeid;
            }
            foreach ($params['shopname'] as $k=>$shopname){
                $data[$k]['shopname']=$shopname;
                $data[$k]['createtime']=time();
            }
            foreach ($data as $k=>$v){
                $data[$k]['total']=$v['number']*$v['price'];
            }
            foreach ($data as $item){
                $number=db('shop')->where('shopid','=',$item['shopid'])->value('number');
                if($number<$item['number']){
                    $this->error('商品库库存不足,请重新填写商品数量',url('sellerbuy/index'));
                }
            }
            $model=new Preshop();
            $isSave=$model->saveAll($data);
            if($isSave){
                return $this->success('商品预选已经提交到平台，请耐心等待平台审核',url('index'));
            }else{
                return $this->error('商品预选错误，请稍后重试',url('index'));
            }
        }else{
            return $this->error('非法提交，没有此方法',url('index'));
        }
    }

    /**
     * 门店商品预选的审核
     */
    public function audit(){
        $model=new Preshop();
        $obj=$model->where('status','=','0')->select();
        $preshop=collection($obj)->toArray();

        $this->assign('preshop',$preshop);
        return $this->fetch();
    }
    public function aduithandle(Request $request){
        if($request->isPost()){
            $params=$request->param('row/a');
            $data=[];
            if(empty($params)) return $this->error('当前没有审核的商品');
            foreach ($params['id'] as $k=>$id){
                $data[$k]['id']=$id;
            }
            foreach ($params['shopid'] as $k=>$shopid){
                $data[$k]['shopid']=$shopid;
            }
            foreach ($params['shopname'] as $k=>$shopname){
                $data[$k]['shopname']=$shopname;
            }
            foreach ($params['price'] as $k=>$price){
                $data[$k]['price']=$price;
            }
            foreach ($params['storeid'] as $k=>$storeid){
                $data[$k]['storeid']=$storeid;
            }
            foreach ($params['total'] as $k=>$total){
                $data[$k]['total']=$total;
            }
            foreach ($params['number'] as $k=>$number){
                $data[$k]['number']=$number;
            }
            //print_r($data);die;
            foreach ($data as $item){
                Db::startTrans();
                try{
                    $shop=db('shop');
                    $new_number=$shop->where('shopid','=',$item['shopid'])->value('number')-$item['number'];//原商品数
                    //1.商品库减少商品
                    $shop->where('shopid','=',$item['shopid'])->setField('number',$new_number);
                    //2.记录平台的资金变动流水
                    db('pmoneylog')->data([
                        'shopid'=>$item['shopid'],
                        'storeid'=>$item['storeid'],
                        'number'=>$item['number'],
                        'price'=>$item['price'],
                        'total'=>$item['total'],
                        'createtime'=>time()
                    ])->insert();
                    //3.给门店加商品数量
                    $storeshopnumber=db('storeshopnumber');
                    $oldnum=$storeshopnumber->where(['shopid'=>$item['shopid'],'storeid'=>$item['storeid']])->value('number');//旧的门店商品数量
                    if($oldnum){//以前进过货，这次跟新
                        $newnum=$oldnum+$item['number'];
                        $storeshopnumber->where(['shopid'=>$item['shopid'],'storeid'=>$item['storeid']])->setField('number',$newnum);
                    }else{//以前没进过货，这次直接插入
                        $storeshopnumber->data([
                            'shopid'=>$item['shopid'],
                            'storeid'=>$item['storeid'],
                            'number'=>$item['number']
                        ])->insert();
                    }
                    //4.修改商品预选表的状态为 1
                    db('preshop')->where('id','=',$item['id'])->setField('status',1);
                    Db::commit();
                }catch(\Exception	$e)	{
                    Db::rollback();
                }

                //点赞的作品到店，发提醒短信功能
                $like=db('workerlike')->where('status','=',1)->select();//用户点赞作品表
                foreach ($like as $vo){
                    $title=db('worker')->where('workerid','=',$vo['workerid'])->value('title');//收藏作品标题
                    if( strpos($item['shopname'],$title) !== false ){////这批进货商品中的商品名字集合
                        //给收藏过作品的用户发
                        $mobile=db('user')->where('id','=',$vo['uid'])->value('mobile');
                        $storename=db('store')->where('storeid','=',$item['storeid'])->value('storename');

                        $sms=new Sms();
                        $sms->notice($mobile,$title,$storename);
                    }
                }

            }

            return $this->success('审核成功');
        }else{
            return $this->error('非法请求');
        }
    }

    public function bak(Request $request)
    {
        if ($request->isPost()) {


            $params = $request->param('row/a');
            $data = [];
            foreach ($params['id'] as $k => $id) {
                $data[$k]['id'] = $id;
            }
            foreach ($params['shopid'] as $k => $shopid) {
                $data[$k]['shopid'] = $shopid;
            }
            foreach ($params['shopname'] as $k => $shopname) {
                $data[$k]['shopname'] = $shopname;
            }
            foreach ($params['price'] as $k => $price) {
                $data[$k]['price'] = $price;
            }
            foreach ($params['storeid'] as $k => $storeid) {
                $data[$k]['storeid'] = $storeid;
            }
            foreach ($params['total'] as $k => $total) {
                $data[$k]['total'] = $total;
            }
            foreach ($params['number'] as $k => $number) {
                $data[$k]['number'] = $number;
            }

            foreach ($data as $item) {

                //5.给门店减少余额，并记录流水
                //查询门店余额，是否够用，如果不够用，请门店去充值
                $store = db('store');
                $storemoney = $store->where('storeid', '=', $item['storeid'])->value('money');
                if ($item['total'] <= $storemoney) {
                    //余额足够，可以审核通过
                    $newstoremoney = $storemoney - $item['total'];
                    $store->where('storeid', '=', $item['storeid'])->setField('money', $newstoremoney);
                    db('smoneylog')->data([
                        'storeid' => $item['storeid'],
                        'shopid' => $item['shopid'],
                        'number' => $item['number'],
                        'price' => $item['price'],
                        'total' => $item['total'],
                        'createtime' => time(),
                        'type' => '-1'/// type=-1 表示当前流水是支出
                    ])->insert();


                    //1.给平台减商品
                    $shop = db('shop');
                    $new_number = $shop->where('shopid', '=', $item['shopid'])->value('number') - $item['number'];//原商品数
                    $shop->where('shopid', '=', $item['shopid'])->setField('number', $new_number);
                    //2.给门店绑定商品
                    $shop->where('shopid', '=', $item['shopid'])->setField('storeid', $item['storeid']);
                    //3.给平台记账 商品减少  资金增加
                    db('pmoneylog')->data([
                        'shopid' => $item['shopid'],
                        'storeid' => $item['storeid'],
                        'number' => $item['number'],
                        'price' => $item['price'],
                        'total' => $item['total'],
                        'createtime' => time()
                    ])->insert();
                    //4.给门店加商品 商品增加
                    db('storeshopnumber')->data([
                        'shopid' => $item['shopid'],
                        'storeid' => $item['storeid'],
                        'number' => $item['number'],
                    ])->insert();

                    //6.修改商品预选表的状态为 1
                    db('preshop')->where('id', '=', $item['id'])->setField('status', 1);


                } else {
                    //余额不够，审核失败，请门店去充值
                    $this->error('门店的当前余额不足以支付本次采购，请店主去充值');
                }
            }

        }else{
            return $this->error('非法请求');
        }
    }
}